import {AfterViewInit, Component, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {
  heightSpread,
  pxToRem,
  WebsocketService,
  MessageService, ModalComponent, BadgePipe
} from '../../../../ng-tools';
import {HttpClient} from '@angular/common/http';
import {Subscription} from 'rxjs';
import {UserService} from '../../../services/api/user.service';
import {ChangePasswordComponent} from '../content/user/change-password/change-password.component';
import {DatePipe} from '@angular/common';
import {Router, NavigationEnd} from '@angular/router';

declare var Notification: any;


export const heightSpreadTrigger = heightSpread(pxToRem(0, 16), '*', '200ms linear');



@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.scss'],
  providers: [WebsocketService, DatePipe, BadgePipe],
  animations: [
    heightSpreadTrigger
  ]
})
export class NavbarComponent implements OnInit, AfterViewInit, OnDestroy {
  private subscriptions = new Subscription();
  @ViewChild('modal') modal: ModalComponent;
  stateExpression = 'start';
  warningSocket;
  userInfo;
  interval: any;

  constructor(private socket: WebsocketService,
              public userService: UserService,
              private router: Router,
  ) {
  }

  ngOnInit() {

    this.getUserInfo();
  }


  getUserInfo() {
    this.userService.userObserver().subscribe((user) => {
      this.userInfo = user;
    });
  }

  signOut() {
    this.userService.get(this.userService.urls.signOut).subscribe(() => {
      this.router.navigateByUrl('/login').catch();
    });
  }


  showUserMenu(): void {
    this.stateExpression = this.stateExpression === 'start' ? 'end' : 'start';
  }


  ngAfterViewInit(): void {
    // 检测路由变化
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.modal.hide();
      }
    });
  }

  ngOnDestroy(): void {
    this.subscriptions.unsubscribe();
    if (this.warningSocket && this.warningSocket.readyState === 1) {
      this.warningSocket.close();
    }
  }

  showPasswordModal() {
    this.stateExpression = 'start';
    this.modal.show({
      title: '修改密码',
      cssIcon: 'fa fa-fw fa-info-circle',
      dynamicComponent: {
        component: ChangePasswordComponent,
        events: {
          success: () => {
            this.modal.hide();
          }
        }
      }
    });
  }
}
